package com.xjoyt.pay.controllers;

import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;

public abstract class AbstractController {
	
	@Value("${api.mongodb.url}")
	private String url;

	protected String getBaseUrl() {
		return url + getHttpServletRequest().getContextPath();
	}

	@Value("${spring.profiles.active}")
	protected String active;

	protected static final Logger logger = LoggerFactory.getLogger(AbstractController.class);

	protected boolean isProduct() {
		return StringUtils.isNotBlank(active)
				&& ("prod".equals(active.toLowerCase()) || "product".equals(active.toLowerCase()));
	}

	protected boolean isDeveloper() {
		return StringUtils.isNotBlank(active) && "dev".equals(active.toLowerCase());
	}

	protected String toJson(Object obj) {
		if (obj == null) {
			return null;
		}
		Gson gson = new Gson();
		String json = gson.toJson(obj);
		return json;
	}

	protected <T> T toObject(String json, Class<T> cls) {
		Gson gson = new Gson();
		return gson.fromJson(json, cls);
	}

	protected String getRequestPath() {
		HttpServletRequest request = getHttpServletRequest();
		String path = request.getContextPath();
		String url = request.getScheme() + "://" + request.getServerName();
		int port = request.getServerPort();
		if (port != 80 && port != 443) {
			url += ":" + port;
		}
		url += path;
		return url;
	}

	protected HttpSession getSession() {
		return getHttpServletRequest().getSession();
	}

	protected ServletRequestAttributes getServletRequestAttributes() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return attrs;
	}

	protected HttpServletRequest getHttpServletRequest() {
		return getServletRequestAttributes().getRequest();
	}

	protected HttpServletResponse getHttpServletResponse() {
		return getServletRequestAttributes().getResponse();
	}

	@ExceptionHandler
	public void exception(HttpServletRequest request, HttpServletResponse response, Exception e) {
		logger.error("服务器发生错误", e);
		StringBuilder builder = new StringBuilder();
		builder.append("\r\n\r\n");
		builder.append("=======================ERROR============================\r\n");
		builder.append("DateTime : " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "\r\n");
		builder.append("URI : [" + request.getRequestURI() + "]\r\n");

		Map<String, String[]> parameters = request.getParameterMap();
		for (Entry<String, String[]> entry : parameters.entrySet()) {
			String key = entry.getKey();
			builder.append("parameter : [" + key + " : " + request.getParameter(key) + "]\r\n");
		}

		builder.append("exception : [" + e.toString() + "]\r\n");
		e.printStackTrace();
		builder.append("========================================================\r\n");
		builder.append("\r\n\r\n");
		System.out.println(builder.toString());
		logger.error(builder.toString());
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		try (PrintWriter writer = response.getWriter()) {
			String json = "服务器发生错误";
			writer.write(json);
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			ex.printStackTrace();
		}
	}
}
